'use strict';
var service = require('service.js');
var config = require('../config/config');
var enum_type = require('../utils/enum');

function saveClickData(params) {
  
  var that = this;
  params.appid = config.appId;
  service.saveClickData(params).then(res => {
    console.log(res);
  }).catch(e => {
    console.log(e);
  })
  
}

/**
 * 更新分享任务
 */
function updateUserTaskComplete(options) {

  let scene = options.scene;
  if (scene == 1007 || scene == 1008) {
    let userId = options.query.userId;
    let taskType = 2;
    service.updateUserTaskComplete({
      userId: userId,
      taskType: taskType
    }).then(res => {
    }).catch(e => {

    })
  }
}

function jumpClickData(customerAppId) {

  var taskType =1;
  var dataPrams = {
    customerAppId: customerAppId,
    jumpType: enum_type.jumpTypeEnum.OUT
  };

  this.saveClickData(dataPrams);
  let userInfo = wx.getStorageSync("userInfo");
  if (userInfo) {
    service.updateUserTaskComplete({
      userId: userInfo.id,
      taskType: taskType
    }).then(res => {
    }).catch(e => {

    })
  }

}

/**
 * 获取导航列表
 */
function getNavlist(cb) {

  var that = this;
  let params={};
  params.appid = config.appId;
  service.getNavlist(params).then(res => {
    cb(res);
  }).catch(e => {
    console.log(e);
  })

}

function adsClickData(options) {

  var source = options.source;
  //广告主跳转进来
  if (source) {
    var dataPrams={};
    dataPrams.source = source;
    dataPrams.jumpType = enum_type.jumpTypeEnum.COMING;
    this.saveClickData(dataPrams);
  }
}

function navigateToH5(h5Url) {
  wx.navigateTo({
    url: '../pages/webview/webview?h5Url=' + h5Url,
  })
}

function navigateToDetail () {
  wx.navigateTo({
    url: '../pages/detail/detail',
  })
}

 function navigateToMiniProgram(appid, page) {
  wx.navigateToMiniProgram({
    appId: appid,
    path: page,
    envVersion: 'trial',
    success(res) {
      // 打开成功
      console.log(res);
    }
  })
}

function jumpPage (event) {

  var item = event.currentTarget.dataset.item;
  var type = event.currentTarget.dataset.type;
  var dataId = item.id;
  //用户点击

  if (item.jumpType == 1) {
    var details = item.detail;
    wx.setStorageSync('details', details);
    this.navigateToDetail();
  } else if (item.jumpType == 2) {
    this.navigateToMiniProgram(item.appId, item.appPage);
  } else if (item.jumpType == 3) {
    this.navigateToH5(item.h5Url);
  } else if (item.jumpType == 4) {
    wx.redirectTo({
      url: "../../" + item.pageUrl,
    })
  }
}

module.exports = {
  saveClickData: saveClickData,
  adsClickData: adsClickData,
  updateUserTaskComplete:updateUserTaskComplete,
  getNavlist:getNavlist,
  navigateToH5: navigateToH5,
  navigateToDetail: navigateToDetail,
  navigateToMiniProgram: navigateToMiniProgram,
  jumpPage: jumpPage,
  jumpClickData: jumpClickData
};